package com.csaba.swing.gui.util;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JMenuItem;

public final class GUIUtil
{
	public final static char MNEMONIC_MARKER = '&';

	private GUIUtil()
	{
		// do not initialize
	}

	/**
	 * Based on the menu text, this method tries to find out the mnemonic key, and set
	 * it on the menu item. The key is find based on a marker character:&. The following
	 * character after the & sign will be the mnemonic.
	 * 
	 * @param menu
	 */
	public static void setMnemonic( final JMenuItem menu )
	{
		String text = menu.getText();

		final int index = text.indexOf(MNEMONIC_MARKER);
		if ( index >= 0 )
		{
			text = text.substring(0, index) + text.substring(index + 1);
			if ( index < text.length() )
				menu.setMnemonic(Character.toLowerCase(text.charAt(index)));

			menu.setText(text);
		}

	}

	public static void setMnemonic( final AbstractAction action )
	{
		String text = (String) action.getValue(Action.NAME);

		final int index = text.indexOf(MNEMONIC_MARKER);
		if ( index >= 0 )
		{
			text = text.substring(0, index) + text.substring(index + 1);
			if ( index < text.length() )
				action.putValue(Action.MNEMONIC_KEY, (int) Character.toLowerCase(text.charAt(index)));

			action.putValue(Action.NAME, text);
		}

	}

}
